import dayjs from "dayjs";

/**
 * 获取最后时间
 * @param {*} t
 * @returns
 */
export const getEndOfDay = (t) => {
    return dayjs(t).endOf("day").format("YYYY-MM-DD HH:mm:ss");
};

/**
 * 获取最开始时间
 * @param {*} t
 * @returns
 */
export const getStartOfDay = (t) => {
    return dayjs(t).startOf("day").format("YYYY-MM-DD HH:mm:ss");
};

/**
 * 格式化传入时间
 * @param t
 * @param format
 * @returns {string|string|string}
 */
export const formatTime = (t, format = "YYYY-MM-DD HH:mm:ss") => {
    if (t === null || t === undefined || t === '') return ''
    return dayjs(t).format(format); // 校验日期有效性
};

// 转换成天时分秒
export function convertHoursToDaysHoursMinutes(minutes) {
    // 一天有 1440 分钟，一小时有 60 分钟
    var MINUTES_IN_DAY = 1440;
    var MINUTES_IN_HOUR = 60;
    var days = Math.floor(minutes / MINUTES_IN_DAY);
    var remainingMinutesAfterDays = minutes % MINUTES_IN_DAY;
    var hours = Math.floor(remainingMinutesAfterDays / MINUTES_IN_HOUR);
    var remainingMinutes = remainingMinutesAfterDays % MINUTES_IN_HOUR;
    return days + "天" + hours + "小时" + remainingMinutes + "分钟";
}

// 比较俩个时间，天数差
export function compareDays(startTime, endTime) {
    var startTime = new Date(startTime);
    var endTime = new Date(endTime);
    var days = (endTime - startTime) / (1 * 24 * 60 * 60 * 1000);
    return days;
}

// 获取当前日期对应的星期
export const getDayOfWeek = (d) => {
    const dayOfWeek = dayjs(d).day();
    const weekDays = [
        "星期日",
        "星期一",
        "星期二",
        "星期三",
        "星期四",
        "星期五",
        "星期六",
    ];
    return weekDays[dayOfWeek];
};

// 返回包括当前和往后六天日期和星期
export const getAfterSixDaysAndWeek = (
    d,
    number = 6,
    options = {
        dateFormat: "YYYY-MM-DD",
    }
) => {
    // 今天
    const today = dayjs();
    // 获取当前日期的后 number 天及对应的星期
    const currentDate = dayjs(d);
    const todayObj = {
        dateFormat: currentDate.format(options.dateFormat),
        dayOfWeek: currentDate.isSame(today, "day")
            ? "今天"
            : getDayOfWeek(currentDate),
        date: currentDate,
    };
    const next6Days = Array.from({length: number}, (_, i) => {
        const date = currentDate.add(i + 1, "day"); // 计算未来日期
        return {
            dateFormat: date.format(options.dateFormat), // 格式化日期为 YYYY-MM-DD
            dayOfWeek: getDayOfWeek(date), // 获取对应的星期几
            date: date,
        };
    });
    return [todayObj, ...next6Days];
};

export const isSame = (date1, date2, unit = "day") => {
    const d1 = dayjs(date1);
    const d2 = dayjs(date2);
    return d1.isSame(d2, unit);
};

export const isSameDay = (date1, date2) => {
    return isSame(date1, date2, "day");
};
